﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
using System.Web.Mvc;

namespace Aga.Psad.Mvc.Helpers
{
    public static class ThemeHelper
    {
        public static string ThemeNameViewDataKey = "ThemeName";
        public static string ThemeRefViewDataKey = "ThemeRef";
        public static string ThemeHiddenId = "ThemeReferenceId";

        public static Dictionary<string, string> Themes = new Dictionary<string, string>();

        static ThemeHelper()
        {
            Themes.Add("cmc", "Campbell");
        }

        public static string GetTheme(NameValueCollection queryString)
        {
            string reference = GetReference(queryString);

            if (!String.IsNullOrEmpty(reference))
            {
                if (Themes.ContainsKey(reference))
                {
                    return Themes[reference];
                }
            }
            return "Default";
        }

        public static string GetTheme(string reference)
        {
            if (!String.IsNullOrEmpty(reference))
            {
                if (Themes.ContainsKey(reference))
                {
                    return Themes[reference];
                }
            }
            return "Default";
        }

        public static object ThemeRouteValue(NameValueCollection queryString)
        {
            string reference = GetReference(queryString);

            if (!String.IsNullOrEmpty(reference))
            {
                return new
                {
                    @ref = reference
                };
            }

            return null;
        }

        public static string GetReference(NameValueCollection queryString)
        {
            string reference = String.Empty;

            if (queryString.AllKeys.Contains("ref"))
            {
                reference = queryString["ref"];
            }

            return reference;
        }

        internal static void SetTheme(NameValueCollection queryString, ViewDataDictionary viewData)
        {
            string reference = GetReference(queryString);

            // if no theme was referenced through the query string
            if (String.IsNullOrEmpty(reference))
            {
                // checks the view data
                reference = (string)viewData[ThemeRefViewDataKey];
            }

            viewData[ThemeNameViewDataKey] = GetTheme(reference);
            viewData[ThemeRefViewDataKey] = reference;
        }
    }
}
